package vectorindex_v2

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cloudwego/eino/schema"
)

// EnsureDirectory 确保目录存在，如果不存在则创建
func EnsureDirectory(dirPath string) error {
	if dirPath == "" {
		return nil
	}
	return os.MkdirAll(dirPath, 0755)
}

// ValidateDocuments 验证文档集合的有效性
func ValidateDocuments(docs []*schema.Document, vectorDim int) error {
	for i, doc := range docs {
		if doc == nil {
			return fmt.Errorf("document at index %d is nil", i)
		}
		if doc.Content == "" {
			return fmt.Errorf("document at index %d has empty content", i)
		}
		if vectorDim > 0 {
			vector := doc.DenseVector()
			if vector == nil || len(vector) != vectorDim {
				return fmt.Errorf("document at index %d has invalid vector dimension", i)
			}
		}
	}
	return nil
}

// CreateTempIndexPath 创建临时索引文件路径
func CreateTempIndexPath(prefix string) (string, string, error) {
	tempDir, err := os.MkdirTemp("", prefix)
	if err != nil {
		return "", "", fmt.Errorf("failed to create temp directory: %w", err)
	}

	indexPath := filepath.Join(tempDir, "index.faiss")
	docPath := filepath.Join(tempDir, "docs.json")

	return indexPath, docPath, nil
}

// BatchProcess 批量处理文档
func BatchProcess(ctx context.Context, docs []*schema.Document, batchSize int, processFn func(context.Context, []*schema.Document) error) error {
	for i := 0; i < len(docs); i += batchSize {
		if ctx.Err() != nil {
			return ctx.Err()
		}

		end := i + batchSize
		if end > len(docs) {
			end = len(docs)
		}

		batch := docs[i:end]
		if err := processFn(ctx, batch); err != nil {
			return fmt.Errorf("failed to process batch starting at %d: %w", i, err)
		}
	}

	return nil
}

// CalculateBatchSize 根据文档数量计算合适的批次大小
func CalculateBatchSize(totalDocs int, maxBatchSize int) int {
	if totalDocs <= maxBatchSize {
		return totalDocs
	}

	// 基本批次大小
	baseBatchSize := totalDocs / 10
	if baseBatchSize < 1 {
		baseBatchSize = 1
	}

	// 确保不超过最大批次大小
	if baseBatchSize > maxBatchSize {
		return maxBatchSize
	}

	return baseBatchSize
}
